"""
杂项工具
"""

from datetime import datetime
import locale
import hashlib
from PyQt5.QtWidgets import QDesktopWidget

__all__ = [
	'get_time', 
	'get_file_md5', 'get_file_name', 'get_relative_folder', 
	'get_upload_chunks','get_chunk_size','center_window_on_screen'
]

def get_time(stamp=False):
	'''获取当前时间戳'''
	if stamp:
		return str(int(datetime.utcnow().timestamp() * 1000))
	else:
		# 在统信UOS上面遇到时间的国际化设置缺省为zh-CN，造成返回时间格式化字符串含有unicode字符，
		# 而当时间字符串作为request的header的某个域时，在header用latin-1编码就会报异常
		locale.setlocale(locale.LC_TIME, (None, None))
		return datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')


def get_file_md5(file_path, check=True):
	if check:
		_md5 = hashlib.md5()
		with open(file_path, 'rb') as f:
			while True:
				data = f.read(64 * 1024)
				if not data:
					break
				_md5.update(data)
			hash_md5 = _md5.hexdigest()
		return hash_md5.upper()
	else:
		return 'random_md5_value'  # TODO: 这里需要返回一个值


def get_file_name(file_path):
	'''文件路径获取文件名'''
	return file_path.strip('/').strip('\\').rsplit('\\', 1)[-1].rsplit('/', 1)[-1]


def get_relative_folder(full_path, work_path, is_file=True):
	'''文件路径获取文件夹'''
	work_name = get_file_name(work_path)
	# 有可能 work_name 在父文件夹中有出现，
	# 因此 反转路径 以替换最后一个文件(夹)名，最后再倒回来 (〒︿〒)
	work_hone = work_path[::-1].strip('/').strip('\\').replace(work_name[::-1], '', 1)[::-1]
	relative_path = full_path.strip('/').strip('\\').replace(work_hone, '')
	file_name = relative_path.rsplit('\\', 1)[-1].rsplit('/', 1)[-1] if is_file else ''
	return relative_path.replace(file_name, '').strip('/').strip('\\')


def get_upload_chunks(file, chunk_size=8096):
	"""文件上传 块生成器"""
	while True:
		data = file.read(chunk_size)
		if not data: break
		yield data


def get_chunk_size(total_size: int) -> int:
	"""根据文件大小返回 块大小"""
	if total_size >= 1 << 30:  # 1 GB
		return  10 << 20  # 10 MB
	elif total_size >= 100 << 20:  # 100 MB
		return 4 << 20  # 4 MB
	elif total_size == -1:
		return 4 << 20  # 4 MB
	else:
		return 1 << 20  # 1 MB

def get_file_size_str(filesize) -> str:
	if not filesize:
		return ''
	filesize = int(filesize)
	if 0 < filesize < 1 << 20:
		return f"{round(filesize/1024, 2)}KB"
	elif 1 << 20 < filesize < 1 << 30:
		return f"{round(filesize/(1 << 20), 2)}MB"
	elif 1 << 30 < filesize < 1 << 40:
		return f"{round(filesize/(1 << 30), 2)}GB"
	elif 1 << 40 < filesize < 1 << 50:
		return f"{round(filesize/(1 << 40), 2)}TB"
	else:
		return f"{filesize}Bytes"

def is_ftype_image(ftype):
	subffix = {'JPG', 'JPEG', 'PNG', 'GIFF', 'WEBP', 'SVG', 'PSD', 'RAW', 'HEIF', 'INDD', 'JPEG 2000', 'BMP', 'AI', 'EPS', 'PDF'}
	return (ftype.upper() in subffix)

def is_ftype_video(ftype):
	subffix = {'MP4', 'AVI', 'WEBM', 'MKV', 'FLV', 'VOB', 'OGV', 'MOV', 'WMV', 'RM', 'RMVB', 'ASF', 'MPG', 'MPEG'}
	return (ftype.upper() in subffix)

def center_window_on_screen(window):
	qtRectangle = window.frameGeometry()
	centerPoint = QDesktopWidget().availableGeometry().center()
	qtRectangle.moveCenter(centerPoint)
	window.move(qtRectangle.topLeft())